const express = require('express');
const image = require('../db/model/image')
const router = express.Router();
const multer = require('multer');
// 配置 Multer 文件上传
// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/'); // 选择保存文件的目录
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname); // 使用原始文件名作为保存的文件名
    }
});

const upload = multer({ storage: storage });
express().use(upload.any())
// 图片上传接口
/**
 * @swagger
 * /api/file/upload:
 *   post:
 *     tags:
 *       - 文件
 *     security:
 *      - CoreAPI: []
 *     summary: 上传图片
 *     consumes:
 *       - multipart/form-data
 *     requestBody:
 *        content:
 *          multipart/form-data:
 *             schema:
 *               type: object
 *               properties:
 *                  file:
 *                      type: string
 *                      format: binary
 *     responses:
 *       200:
 *         description: 成功上传图片并返回图片路径
 *         schema:
 *           type: object
 *           properties:
 *             path:
 *               type: string
 *               description: 图片的服务器路径
 */
router.post('/upload', upload.single('file'), async (req, res) => {

    try {
        console.log(req.file);
        const { originalname, mimetype } = req.file
        // 创建 Image 记录
        const Image = await image.create({
            filename: originalname,
            mimetype,
            path: 'http://127.0.0.1:5000/uploads/' + originalname
        });

        res.send({
            status: 200,
            data: {
                picUrl: Image.path
            },
            message: '上传成功！'
        })
    } catch (error) {
        console.error('图片上传失败：', error);
        res.status(500).json({ error: '图片上传失败' });
    }
});
module.exports = router